package com.evolve.autotest.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtil {
	
	/**
	 * Gets the simple name from a file. Will
	 * remove the path and the file ending
	 * @param file
	 * @return
	 */
	public static String extractSimpleName(final File file) {
		String name = file.getName();
		
		if (name.contains(".")) {
			int index = name.indexOf(".");
			
			name = name.substring(0, index);
		}
		
		return name;
	}
	
	/**
	 * Reads the content of a file
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	public static String readFileContent(File file) throws IOException {
		if (file == null) {
			throw new IllegalArgumentException("file is null");
		}
		
		BufferedReader reader = null;
		StringBuffer buffer = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			
			String line = "";
			while((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
		
		return buffer.toString();
	}	
	
	/**
	 * Writes the output to file
	 * @param output
	 * @param outputDirectory
	 * @throws IOException 
	 */
	public static void writeOutput(String output, File file) throws IOException {

		FileWriter writer = null;
		try {
			writer = new FileWriter(file);
			writer.write(output);
		} catch (IOException e) {
			throw e;
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
	}
}
